﻿/// Copyright © 2013 Microsoft Corporation. 
/// This project is released under the Microsoft Public License (MS-PL)
///
namespace Azure.Performance
{
    using System;
    using System.IO;

    using Microsoft.WindowsAzure.ServiceRuntime;
    
    //NOTE: Make some configruation changes to your environment in order to run this
    //http://blogs.msdn.com/b/seendabean/archive/2012/06/25/fileloadexception-in-unit-test-on-roleenvironment-isavailable-with-visual-studio-2012-rc-with-azure-sdk-1-7.aspx
    
    public class TestFile
    {
        /// <summary>
        /// Get's a test file for upload of a given size in MB.
        /// The method will create a file in the file system if one of that size does not already exist
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string GetFile(int size)
        {
            string testFile = GetTestFilePath(size);

            //If the sample file already exists just return that
            if (File.Exists(testFile))
                return testFile;

            //Create a file and return the path
            using (var fs = File.Create(testFile))
            {

                //Create a 1MB buffer and write some data to our file
                var buffer = new byte[1024 * 1024];
                var rand = new Random();

                for (var i = 0; i < size; i++)
                {

                    rand.NextBytes(buffer);

                    fs.Write(buffer, 0, buffer.Length);
                }
            }

            return testFile;
        }

        private static string GetTestFilePath(int filesize)
        {
            return Path.Combine(WorkPath, filesize + "mb.bin");
        }

        private static string WorkPath
        {
            get
            {
                var basePath = RoleEnvironment.IsAvailable ? RoleEnvironment.GetLocalResource("Temp").RootPath : Path.GetTempPath();
                        
                var workPath = Path.Combine(basePath, "___UploadTestFiles");

                Directory.CreateDirectory(workPath);

                return workPath;
            }
        }

        public static void Clean()
        {
            var workPath = WorkPath;
            
            //Delete all files in the directory
            foreach (var file in Directory.GetFiles(workPath))
            {
                File.Delete(file);
            }

            //Delete the work directory
            Directory.Delete(workPath);
        }
    }
}